package com.hp.bon.sgw.threads;

import static com.hp.bon.sgw.Constants.LOG;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.LoggerFactory;

public abstract class LogCacheManager extends TaskThread {
	
	private static int BUFFER_MAX_NUM = 10240;
	public ArrayList<Object> logObjectBuffer = new ArrayList<Object>(BUFFER_MAX_NUM);
	final public static org.slf4j.Logger LOG = LoggerFactory.getLogger(LogCacheManager.class);
	
	/**
	 * 先执行父类的构造函数，再执行子类的构造函数
	 */
	public LogCacheManager()
	{
		this.sleepTime = 500;
	}
	
	public void add(Object e) {
		boolean isBusy = false;
		synchronized (logObjectBuffer) {
			if (logObjectBuffer.size() < BUFFER_MAX_NUM * 2) {
				logObjectBuffer.add(e);
			} else {
				isBusy = true;
			}
		}
		if (isBusy) {
			flush2File(e);
		}
	}

	public abstract void flush2File(Object e);

	@SuppressWarnings("unchecked")
	public void process() {
		if (logObjectBuffer.size() > 0) {
			ArrayList<Object> tempList;
			synchronized (logObjectBuffer) {
				tempList = (ArrayList<Object>) logObjectBuffer.clone();
				logObjectBuffer.clear();
			}
			flush2BD(tempList);
			if (LOG.isDebugEnabled()) {
				StringBuilder sb = new StringBuilder();
				sb.append(this.getName()).append(" flush records num =");
				sb.append(tempList.size()).append(",time(ms)=").append(System.currentTimeMillis() - this.runTime);
				LOG.debug(sb.toString());
			}
		}
	}
	protected void processBeforeExit() {
		if (logObjectBuffer.size() != 0) {
			flush2BD((List<Object>) logObjectBuffer);
		}
	}
	protected abstract void flush2BD(List<Object> tempList);

}
